"use strict";
import React from "react";
import $ from "jquery";
import hash from "object-hash";
import lscache from "lscache";

var ReactHighcharts = require("react-highcharts/dist/bundle/highcharts"); // Expects that Highcharts was loaded in the code. 
import { hColumn2DConfig, hPie2DConfig, hArea2DConfig, hLineConfig } from "../common/hchartconfig.js";

var GOTOMixin = {
	gotoIndex: function(){
		// 首页
		// this.state.params.mod = undefined;
		this.history.pushState(null, '/index');
	},

	gotoTrading: function(event){
		// 交易
		var showDiv = $(event.target).attr('data-div');

		if (showDiv) {
			lscache.set('showDiv', showDiv, 60 * 24 * 30);
		} else {
			showDiv = lscache.get('showDiv');
			if (showDiv == 0) {
				this.gotoIndex();
				return;
			}
		}
		var query = {};
		
		this.history.pushState(null, '/trading', query);
	},
	gotoTradingDetail: function(event) {
		var showDiv = $(event.target).parent().attr('data-div');
		var targetDetail = $(event.target).parent().attr('data-detail');

		if (showDiv) {
			lscache.set('showDiv', showDiv, 60 * 24 * 30);
		}

		switch(targetDetail) {
			case 'AUM': this.gotoTradingAUM(); break;
			case 'SCFE': this.gotoTradingSCFE(); break;
			case 'KHS': this.gotoClientKHS(); break;
			case 'XZYXH': this.gotoClientXZYXH(); break;
			case 'LRZJC': this.gotoTradingLRZJC(); break;
		}
	},
	gotoTradingAUM: function(event){
		// 交易 AUM
		var query = {page: 'AUM'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingVolume: function(){
		// 交易 成交量
		var query = {page: 'VOLUME'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingSCFE: function(){
		var query = {page: 'SCFE'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingYJSR: function(){
		// 交易 佣金收入
		var query = {page: 'YJSR'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);	
	},
	gotoTradingYJFL: function(){
		// 交易 佣金费率
		var query = {page: 'YJFL'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingBZJS: function(){
		// 交易 保证金数
		var query = {page: 'BZJS'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingJYKHS: function(){
		// 交易 交易客户数
		var query = {page: 'JYKHS'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingLRZJC: function(){
		// 交易 两融资金池
		var query = {page: 'LRZJC'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingYDGH: function(){
		// 交易 约定购回
		var query = {page: 'YDGH'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingGPZY: function(){
		// 交易 股票质押
		var query = {page: 'GPZY'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingRZPSJ: function(){
		// 交易 融资盘数据
		var query = {page: 'RZPSJ'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoTradingCCSZ: function(){
		// 交易 持仓市值
		var query = {page: 'CCSZ'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/trading/detail', query);
	},
	gotoClient: function(event){
		// 客户数据
		var showDiv = $(event.target).attr('data-div');

		if (showDiv) {
			lscache.set('showDiv', showDiv, 60 * 24 * 30);
		} else {
			showDiv = lscache.get('showDiv');
			if (showDiv == 0) {
				this.gotoIndex();
				return;
			}
		}

		var query = {};
		this.history.pushState(null, '/client', query);
	},
	gotoClientTotal: function(){
		// 总客户
		var query = {page: 'TOTAL'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientKHS: function(){
		// 开户数
		var query = {page: 'KHS'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientXZYXH: function(){
		// 新增有效户
		var query = {page: 'XZYXH'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientXZCFQY: function(){
		// 新增财富签约
		var query = {page: 'XZCFQY'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientXZZCS: function(){
		// 新增资产数
		var query = {page: 'XZZCS'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientXHS: function(){
		// 销户数
		var query = {page: 'XHS'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientLSZC: function(){
		// 流失资产
		var query = {page: 'LSZC'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	gotoClientCLZC: function(){
		// 存量资产
		var query = {page: 'CLZC'};
		this.setState({disableChart: true});
		this.history.pushState(null, '/client/detail', query);
	},
	
	gotoProduct: function(){
		// 产品数据
		var query = {page: this.props.location.query.page};
		this.history.pushState(null, '/product', query);
	},
	gotoProductSFOM: function(){
		// 股基占有率
		var query = {page: 'SFOM'};
		this.history.pushState(null, '/product/detail', query);
	},
	gotoProductPublic: function(){
		// 公募类
		var query = {page: 'public'};
		this.history.pushState(null, '/product/detail', query);
	},
	gotoProductFixed: function(){
		// 固收类
		var query = {page: 'fixed'};
		this.history.pushState(null, '/product/detail', query);
	},
	gotoProductEquity: function(){
		// 权益类
		var query = {page: 'equity'};
		this.history.pushState(null, '/product/detail', query);
	},
	gotoSearch: function(){
		// 搜索
		this.state.params.pre = location.hash;
		this.history.pushState(null, '/search', this.state.params);
	},
	gotoHelp: function(){
		// 帮助
		this.history.pushState(null, '/help');
	},
	goBackward: function(){
		//返回
		this.history.goBack(this.state.params);
	},
};

const FusionChartMixin = {
	fusionCharts: {}, // key: data
	fusionMd5: {}, // key: data md5
	fusionInsts: {}, // key: chart instance
	fusionTimestamp: Date.now(),
	addChart: function(renderId, data){
		// renderId is parent ID, MUST unique
		this.fusionCharts[renderId] = data;
	},
	removeChart: function(renderId){
		$('#' + renderId).empty();
		if(this.fusionInsts.hasOwnProperty(renderId)){
			this.fusionInsts[renderId].dispose();
		}
		delete this.fusionInsts[renderId];
		delete this.fusionCharts[renderId];
		delete this.fusionMd5[renderId];
		console.log('remove:', renderId)
	},
	componentDidMount: function(){
		// this.renderAll()
	},
	componentDidUpdate: function(){
		this.renderAll()
	},
	componentWillUnmount: function(){
		for(var key in this.fusionCharts){
			if(this.fusionCharts.hasOwnProperty(key) == false){
				continue
			}
			this.removeChart(key);
			$('#' + key).empty();
		}
		for(var key in this.fusionInsts){
			if(this.fusionInsts.hasOwnProperty(key)){
				this.fusionInsts[key].dispose();
			}
		}
		this.fusionCharts = null;
		this.fusionInsts = null;
		this.fusionMd5 = null;
	},
	renderAll: function(){
		for(var key in this.fusionCharts){
			if(this.fusionCharts.hasOwnProperty(key) == false){
				continue
			}
			// render
			var data = this.fusionCharts[key];
			// 判断是否已经渲染
			var md5 = hash.MD5(data);
			// 数据无变化，退出
			if(this.fusionMd5.hasOwnProperty(key) && this.fusionMd5[key] == md5){
				console.log('no change:')
				continue
			}
			this.fusionMd5[key] = md5;
			// 数据为空
			if(data && data.dataSource && data.dataSource.data && data.dataSource.data.length == 0){
	            return
        	}
        	if(data && data.dataSource && data.dataSource.dataset && data.dataSource.dataset.length == 0){
            	return
        	}
        	if(this.fusionInsts.hasOwnProperty(key)){
        		var chart = this.fusionInsts[key]
        		chart.dispose();
        	}
        	console.log('new chart', key, md5)
        	data.renderAt = key;
        	var myChart = new FusionCharts(data);
	        myChart.configure("PBarLoadingText", "　　");
	        // Render the chart.
	        myChart.render();
	        this.fusionInsts[key] = myChart;
	    }
	}
};

const HighChartMixin = {
	highChartInsts: {},
	getHighChart: function(config){
		if(config == null){
			return null;
		}

		var md5 = hash.MD5(config);
		if(this.highChartInsts.hasOwnProperty(md5)){
			return this.highChartInsts[md5];
		}
		var chart = <ReactHighcharts config = {config}></ReactHighcharts>;
		this.highChartInsts[md5] = chart;
		return chart;
	},
	getHColumn2DConfig: function(values, params){
		params = (params==null? {}: params);
		var unit = params['unit'];

		var config = $.extend(true, {}, hColumn2DConfig);
		if(values == null || values.length == 0)
			return config;
		var dataset = [];
		var category = [];

		var temp = {};
		if (values[0].ex_date != undefined) {
			for (var i = 0; i < values.length; i++) {
				var item = values[i];
				category.push(item.ex_date);
				for (var j = 0; j < item.data.length; j++) {
					var item1 = item.data[j];
					if (!temp.hasOwnProperty(item1.label)) {
						temp[item1.label] = [];
					}
					item1.value = item1.value == null ? 0 : item1.value;
					temp[item1.label].push(parseFloat(item1.value));
					}
				}
			}
		
			for (var item in temp) {
				dataset.push({name: item, data: temp[item]});
		}

		// 控制X坐标展示
		// if(category.length > 3){
		// 	var showY = [0, parseInt(category.length / 2), category.length - 1];
		// 	for(var i=0; i<category.length; i++){
		// 		if(showY.indexOf(i) >= 0){
		// 			continue
		// 		}
		// 		category[i] = '';
		// 	}
		// }

		config.xAxis.categories = category;
		config.xAxis.labels.step = category.length - 1;
		unit = (unit == null? '': unit);
		config.tooltip.pointFormat = '<tr><td style="color:{series.color};padding:0">{series.name}：</td>' +
            '<td style="padding:0"><span style="opacity:0.8">{point.y:.2f}'+unit+'</span></td></tr>'
		config.series = dataset;
		return config;
	},
	getHArea2DConfig: function(values, params){
		params = (params==null? {}: params);
		var unit = params['unit'];

		var config = $.extend(true, {}, hArea2DConfig);
		if(values == null || values.length == 0){
			return config;
		}

		var dataset = [];
		var category = [];

		var temp = {};
		if (values[0].ex_date != undefined) {
			for (var i = 0; i < values.length; i++) {
				var item = values[i];
				category.push(item.ex_date);
				for (var j = 0; j < item.data.length; j++) {
					var item1 = item.data[j];
					if (!temp.hasOwnProperty(item1.label)) {
						temp[item1.label] = [];
					}
					item1.value = item1.value == null ? 0 : item1.value;
					temp[item1.label].push(item1.value);
					}
				}
			}
		
			for (var item in temp) {
				dataset.push({name: item, data: temp[item]});
		}

		// 控制X坐标展示
		// if(category.length > 3){
		// 	var showY = [0, parseInt(category.length / 2), category.length - 1];
		// 	for(var i=0; i<category.length; i++){
		// 		if(showY.indexOf(i) >= 0){
		// 			continue
		// 		}
		// 		category[i] = '';
		// 	}
		// }

		config.xAxis.categories = category;
		config.xAxis.labels.step = category.length - 1;
		unit = (unit == null? '': unit);
		config.tooltip.pointFormat = '<tr><td style="color:{series.color};padding:0">{series.name}：</td>' +
            '<td style="padding:0"><span style="opacity:0.8">{point.y:.2f}'+unit+'</span></td></tr>'
		config.series = dataset;
		return config;
	},
	getHPie2DConfig: function(values, params){
		params = (params==null? {}: params);
		var height = params['height'];
		var backgroundColor = params['backgroundColor'];

		// values: [{label:xxx, value:xxx}, {label:xxx, value:xxx}]
		var config = $.extend(true, {}, hPie2DConfig);
		if(backgroundColor){
			config.chart.backgroundColor = backgroundColor;
		}
		if(height==null){
			config.chart.height = screen.width*0.45 - 15;
		}
		else{
			config.chart.height = height;
		}

		if(values == null || values.length == 0){
			return config;
		}

		if(values == null || values.length == 0){
			return config;
		}
		var data = values.map(function(item){
			return {name: item.label, y: item.value}
		});
		config.series[0].data = data;

		return config;
	},
	getHLineConfig: function(values, params){
		params = (params == null? {}: params);
		var unit = params['unit'];

		var config = $.extend(true, {}, hLineConfig);

		if(values == null || values.length == 0){
			return config;
		}
		var dataset = [];
		var category = [];

		if (values[0].ex_date != undefined) {
			var temp = {};
			for (var i = 0; i < values.length; i++) {
				var item = values[i];
				category.push(item.ex_date);
				for (var j = 0; j < item.data.length; j++) {
					var item1 = item.data[j];
					if (!temp.hasOwnProperty(item1.label)) {
						temp[item1.label] = [];
					}
					item1.value = item1.value == null ? 0 : item1.value;
					temp[item1.label].push(parseFloat(item1.value));
				}
			}
		}
		for (var item in temp) {
			dataset.push({name: item, data: temp[item]});
		}

		if(unit){
			config.tooltip.pointFormat = '{series.name}：<b>{point.y:,.2f}'+unit+'</b>';
		}
		config.xAxis.categories = category;
		config.xAxis.labels.step = category.length - 1;	
		config.series = dataset;
		config.height = 190;

		return config;
	},
};

export { GOTOMixin, FusionChartMixin, HighChartMixin };